// socket功能
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import { v4 as uuidv4 } from "uuid";

const baseURL = process.env.VUE_APP_SOCKET_URL; //process.env.VUE_APP_BASE_URL;
const AUTH_KEY = "ws-auth-token";

export function connectionSocket() {
  return new Promise((resolve) => {
    const uuid = localStorage.getItem(AUTH_KEY)
      ? localStorage.getItem(AUTH_KEY)
      : uuidv4();

    const socketUrl = baseURL + `websocket?${AUTH_KEY}=${uuid}`;

    let socket = new SockJS(socketUrl); //连接SockJS的endpoint名称为"bullet"
    console.log("socket连接地址:" + socketUrl);
    // 获取STOMP子协议的客户端对象
    let stompClient = Stomp.over(socket);

    // 拦截输出的一大堆垃圾信息
    //   stompClient.debug = function (str) {
    //     $("#debug").append(str + "\n");
    //   };
    // 向服务器发起websocket连接
    stompClient.connect(
      { "ws-auth-token": uuid },
      () => {
        // stompClient.subscribe("/user/stomp/scanBindUserQrCode", (response) => {
        //   // 订阅服务端提供的某个topic
        //   if (response.body) {
        //   }
        // });

        stompClient.subscribe("/user/stomp/scanLoginQrCode", (response) => {
          // 订阅服务端提供的某个topic
          if (response.body) {
            //   将authToken存储
            localStorage.setItem("userinfo", response.body);
            resolve(response.body);
          }
        });
      },
      (err) => {
        // 连接发生错误时的处理函数
        console.log(err);
      }
    );
  });
}
